package com.streamer.app.utils;

import static com.streamer.app.StreamerApplication.instance;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;



public class ToastUtil {

    private static Toast toast;

    public static void toastLongMessage(final String message) {
        toastMessage(message, true);
    }

    public static void toastShortMessage(final String message) {
        toastMessage(message, false);
    }

    private static void toastMessage(final String message, boolean isLong) {
        if (TextUtils.isEmpty(message)) return;
        
        // 检查instance是否为空
        if (instance == null) {
            // 如果instance为空，直接返回，避免崩溃
            return;
        }
        
        BackgroundTasks.getInstance().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (toast != null) {
                        toast.cancel();
                        toast = null;
                    }
                    
                    // 再次检查instance是否为空
                    if (instance != null) {
                        toast = Toast.makeText(instance, message,
                                isLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
                        View view = toast.getView();
                        if (view != null) {
                            TextView textView = view.findViewById(android.R.id.message);
                            if (textView != null) {
                                textView.setGravity(Gravity.CENTER);
                            }
                        }
                        toast.show();
                    }
                } catch (Exception e) {
                    // 捕获所有异常，避免崩溃
                    e.printStackTrace();
                }
            }
        });
    }

}
